//
//  HTControlView.swift
//  MagaCore
//
//  Created by MrMessy on 2023/6/7.
//

import SwiftUI
import AVKit
import AppLovinSDK

struct HTControlView: View {
  let var_margin: CGFloat = 15
  let var_progressWidth: CGFloat = var_screenWidth - 2*15 - 22*2 - 57*2 - 16*2

  @Binding var var_palyer: AVPlayer
  @Binding var var_subTitleBtnClick: (() -> Void)!
  @Binding var var_fullScreen: ((UIDeviceOrientation) -> Void)!
  @Binding var var_subState: HTEnumSubtitleState!
  @Binding var var_progressRate: Double!
  @Binding var var_startTime: String
  @Binding var var_endTime: String
  @Binding var var_during: Double
  @Binding var var_isSuspend: Bool        // 是否暂停
  @Binding var var_isShowControls: Bool

  @Environment(\.presentationMode) private var var_presentationMode: Binding<PresentationMode>
  @EnvironmentObject private var var_store: HTAppStore
  @State private var var_controlsDelayTask: DispatchWorkItem = DispatchWorkItem {}

  var body: some View {
    ZStack{
      if var_isShowControls {
        VStack(alignment: .center, spacing: 0){
          HStack(alignment: .center, spacing: 0){
            HTDefaultBackButton(tapAction: {
              self.var_presentationMode.wrappedValue.dismiss()
            }, isBlack: false, foreground: Color.white)
            .frame(width: 6.5, height: 14.5, alignment: .leading)
            .padding(.leading, 20)
            Spacer()
            HTShareButton()
            HStack {
              if var_subState == .htEnumDisable {
                Image("subtitle_disable")
                  .ht_resizeToFit()
                  .frame(width: 40, height: 22)
                  .padding(.leading, 21)
                  .padding(.trailing, var_margin * 2)
              } else {
                Button {
                  var_subTitleBtnClick()
                } label: {
                  if var_subState == .htEnumOpen {
                    Image("subtitle_open")
                      .ht_resizeToFit()
                      .frame(width: 40, height: 22)
                      .padding(.leading, 21)
                  } else if var_subState == .htEnumClose {
                    Image("subtitle")
                      .ht_resizeToFit()
                      .frame(width: 40, height: 22)
                      .padding(.leading, 21)
                  }
                }.padding(.trailing, var_margin * 2)
              }
            }
          }
          .frame(width: var_screenWidth, height: 48)
          .background(LinearGradient(gradient: Gradient(colors: [Color(white: 0, opacity: 1), Color(white: 0, opacity: 0)]), startPoint: .top, endPoint: .bottom))

          Spacer()

          // 中间
          HStack() {
            Button() {
              ht_startOrSuspend()
            }label: {
              ZStack{
                Text("").frame(width: 44, height: 44).background(Color(UIColor(white: 0, alpha: 0.25))).cornerRadius(22)
                if var_isSuspend {
                  Image("start_triangle")
                } else {
                  Image("suspend")
                }
              }.frame(alignment: .center)
            }
          }
          .frame(maxWidth: .infinity, maxHeight: .infinity)

          Spacer()
          HStack(alignment: .center, spacing: 0){
            Button {
              ht_startOrSuspend()
            }label: {
              if var_isSuspend {
                Image("start_triangle").frame(width: 20, height: 20)
              } else {
                Image("suspend").frame(width: 20, height: 20)
              }
            }.padding(.leading, var_margin)
            Spacer()
            HStack(alignment: .center) {
              Text(var_endTime.count > 5 && var_startTime.count < 6 ? "00:" + var_startTime : var_startTime)
                .font(.system(size: 13))
                .foregroundColor(Color.white)
                .frame(width: var_endTime.count > 5 ? 57 : 37, alignment: .trailing)
                .padding(.trailing, 5)
              ZStack(alignment: .leading){
                Capsule()
                  .fill(Color(white: 1, opacity: 0.3))
                  .frame(width: var_progressWidth, height: 2, alignment: .leading)
                Capsule()
                  .fill(Color(hex: "ffffff"))
                  .frame(width: var_progressWidth * var_progressRate, height: 2)
                Text("").frame(width: 8, height: 8)
                  .background(Color(hex: "ffffff")).cornerRadius(4)
                  .offset(x: var_progressWidth * var_progressRate - 4)
                  .gesture(DragGesture(minimumDistance: 0)
                    .onChanged({ value in
                      if (value.location.x < 0) {
                        return
                      }
                      var_progressRate = value.location.x / var_progressWidth
                      if value.location.x > var_progressWidth {
                        var_progressRate = 1.0
                      }
                      if !var_isSuspend {
                        var_palyer.pause()
                      }
                      var_startTime = Int(var_during * var_progressRate).ht_formatTimeLine()
                    }).onEnded({ value in
                      ht_seek(second: var_during * var_progressRate)
                      if !var_isSuspend {
                        var_palyer.play()
                      }
                    })
                  )
              }
              .frame(width:var_progressWidth, height: 30)
              .background(Color.clear)
              .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ val in
                var_progressRate = val.location.x / var_progressWidth
                ht_seek(second: var_during * var_progressRate)
              }))
              Text(var_endTime)
                .font(.system(size: 13))
                .foregroundColor(Color.white)
                .frame(width: var_endTime.count > 5 ? 57 : 37, alignment: .leading)
                .padding(.leading, 5)
            }
            Spacer()
            Button {
              var_fullScreen(.landscapeLeft)
            }label: {
              Image("full_screen")
                .frame(width: 22, height: 22)
            }
            .padding(.trailing, var_margin)
          }
          .frame(width: var_screenWidth, height: 40, alignment: .leading)
          .background(LinearGradient(gradient: Gradient(colors: [Color(white: 0, opacity: 0), Color(white: 0, opacity: 0.5)]), startPoint: .top, endPoint: .bottom))
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .onChange(of: var_isShowControls, perform: { newValue in
      if (newValue) {
        var_controlsDelayTask = DispatchWorkItem {
          var_isShowControls = false
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: var_controlsDelayTask)
      } else {
        var_controlsDelayTask.cancel()
      }
    })
  }

  func ht_startOrSuspend() {
    if var_palyer.rate == 0.0 {
      var_palyer.play()
      var_isSuspend = false
    } else {
      var_palyer.pause()
      var_isSuspend = true
    }
  }

  // 精确定位
  func ht_seek(second: Float64) {
    let var_timeScale = var_palyer.currentItem?.asset.duration.timescale
    let var_time = CMTimeMakeWithSeconds(second, preferredTimescale: var_timeScale ?? 1)
    var_palyer.seek(to: var_time, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
  }
}
